<template>
  <div class="container">
    <div class="app-container">
      <!-- 右上角：添加角色按钮 -->
      <div style="padding: 10px;">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 中间：角色列表表格 -->
      <el-table :data="roleList">
        <el-table-column prop="name" label="角色" align="center" width="200">
          <template #default="{row}">
            <!-- 存在问题: 用于显示和编辑的都是同一份数据,造成用户即使取消编辑,也会修改数据 -->
            <!-- 解决方案: 因为用于显示和编辑的都是同一份数据,所以需要准备两份数据,一份给用户看,一份给用户编辑 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state===1 ? '已启用': row.state === 0 ? '未启用': '其他' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" :rows="2" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <div v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="editConfiemClick(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </div>
            <div v-else>
              <el-button type="text" size="mini" @click="permBtnClick(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editClick(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="delConfiemClick(row)"
              >
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 右下角：角色列表分页 -->
      <el-row type="flex" justify="end" style="height: 40px;" align="middle">
        <el-pagination
          layout="prev, pager, next"
          :total="pageParams.total"
          :current-page="pageParams.page"
          :page-size="pageParams.pagesize"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 新增角色弹层组件 -->
    <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="cancelClick">
      <!-- 角色表单 -->
      <el-form ref="roleForm" label-width="100px" :model="roleForm" :rules="roleRules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" size="mini" style="width: 300px" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" :rows="3" type="textarea" size="mini" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-row style="width: 300px" type="flex" justify="center">
            <el-button size="mini" type="primary" @click="confiemClick">确定</el-button>
            <el-button size="mini" @click="cancelClick">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限弹层组件 -->
    <el-dialog title="分配权限" :visible.sync="showPermDialog" @close="close">
      <el-tree ref="permTree" node-key="id" :data="permList" :props="{label:'name'}" default-expand-all show-checkbox check-strictly />
      <el-row type="flex" justify="center">
        <el-button size="mini" type="primary" @click="assignPermClick">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleAPI, assignPermAPI, delRoleAPI, getRoleAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPermissionsAPI } from '@/api/permission'

export default {
  name: 'Role',
  data() {
    return {
      roleForm: {
        name: '',
        description: '',
        state: 1
      },
      showDialog: false,
      // 角色列表
      roleList: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 一页几条
        total: 0 // 总数
      },
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showPermDialog: false,
      permList: [],
      currentID: null
    }
  },
  created() {
    // 获取角色列表数据
    this.getRoleList()
  },
  methods: {
    // 确定按钮点击事件
    async assignPermClick() {
      // 调分配权限接口
      await assignPermAPI({
        id: this.currentID,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.close()
    },
    close() {
      // 关闭弹层
      this.showPermDialog = false
      // 这里不需要this.$nextTick(): 用户都在点击弹层关闭按钮了，说明tree组件肯定在页面上了
      this.$refs.permTree.setCheckedKeys([])
    },
    // 分配权限按钮点击事件
    async permBtnClick(id) {
      this.currentID = id
      this.showPermDialog = true
      // 调分配权限接口   将数据转成树形结构
      this.permList = transListToTreeData(await getPermissionsAPI())
      // 获取角色详情
      const { permIds } = await getRoleDetailAPI(id)
      // 节点中的复选框默认选中状态
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    // 删除角色
    async delConfiemClick(row) {
      // 调用接口删除角色
      await delRoleAPI(row.id)
      // 提示用户
      this.$message.success('删除角色成功')
      // 判断是否是这一页的最后一条
      if (this.pageParams.page > 1 && this.roleList.length === 1) {
        this.pageParams.page--
      }
      // 重新加载数据
      this.getRoleList()
    },
    // 编辑的确定按钮点击事件
    async editConfiemClick(row) {
      // 手写校验
      if (row.editRow.name && row.editRow.description) {
        // 调接口修改数据
        await updateRoleAPI({ ...row.editRow, id: row.id })
        // 提示用户
        this.$message.success('修改角色成功')
        // 展示编辑后的数据(方法一): editRow(编辑后的数据) -------> row(给用户看是数据)
        // Object.assign(row, { ...row.editRow, isEdit: false })
        // 展示编辑后的数据(方法二): 刷新页面
        this.getRoleList()
      } else {
        this.$message.error('角色名称和角色描述不能为空')
      }
    },
    // 编辑按钮点击事件
    editClick(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.description = row.description
      row.editRow.state = row.state
    },
    // 确定点击事件
    confiemClick() {
      this.$refs.roleForm.validate(async(isOK) => {
        if (isOK) {
          // 调新增接口
          await addRoleAPI(this.roleForm)
          // 提示用户
          this.$message.success('添加角色成功')
          // 刷新页面
          this.getRoleList()
          // 关闭弹层 + 清空表单验证
          this.cancelClick()
        }
      })
    },
    // 关闭点击事件
    cancelClick() {
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 页码切换
    handleCurrentChange(currentPage) {
      this.pageParams.page = currentPage
      this.getRoleList()
    },
    // 调用角色列表接口
    async getRoleList() {
      const { rows, total } = await getRoleAPI(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // 添加响应式数据
        // 语法： $set(目标对象，'')
        this.$set(item, 'isEdit', false)
        // 给每行的原始数据备份
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    }
  }
}
</script>
